import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

let store= new Vuex.Store({
  state: {
    token:'',
    cartarry:JSON.parse(localStorage.getItem('cartarry')) || []//存储购物车商品的数组
  },
  mutations: {
    settoken(state,token){
      state.token=token;
    },
    //添加商品到购物车
    tocart(state,tag){
      let goods=state.cartarry.find(v=>v.title==tag.label)
      if (goods) {
        goods.cartcount+=1
      }else{
        state.cartarry.push({title:tag.label, cartcount:1})
      }
    },
    addcart(state,index){
      state.cartarry[index].cartcount++
    },
    removecart(state,index){
      if(state.cartarry[index].cartcount>1){
       state.cartarry[index].cartcount--
      }else{
        if(window.confirm('确定从购物车删掉吗?')){
          state.cartarry.splice(index,1)
        }
      }
    },
    clearcart(state){
      state.cartarry=[]
    }
  },
  actions: {

  },
  getters:{
    countsum:state=>{
      let num=0
      state.cartarry.forEach(v=>{
        num+=v.cartcount
      })
      return num
    }
  }
})

//监听每次调用mutation的时候，都会进入这个方法，订阅 store 的 mutation。handler 会在每个 mutation 完成后调用
store.subscribe((mutations,state)=>{
  window.localStorage.setItem('cartarry',JSON.stringify(state.cartarry))
})
export default store
